import * as config from 'src/config'
import {
  hasProp
} from 'src/common/util'
import Axios from 'axios'
import qs from 'qs'

export const axios = Axios.create({
  baseURL: config.domain
})

/**
 * @param params post请求提交参数
 * @return URLSearchParams对象
 */
export const _PostParams = (params, prefix = null) => {
  const data = new URLSearchParams()

  if (hasProp(params)) {
    let _params = {}
    if (prefix != null) {
      prefix += '.'
      for (let key in params) {
        _params[prefix + key] = params[key]
      }
    }
    _params = hasProp(_params) ? _params : params
    for (let key in _params) {
      data.append(key, _params[key])
    }
  }
  return data
}

/**
 * 封装请求提交参数
 * @param params post请求提交对象
 * @param prefix 提交key前缀
 */
export const PostParams = (params, prefix = null) => {
  if (params && prefix) {
    let _params = {}
    prefix += '.'
    for (let key in params) {
      _params[prefix + key] = params[key]
    }
    params = _params
  }
  return qs.stringify(params)
}